<template>
  <a-drawer
    v-model:visible="visible"
    class="custom-class"
    style="color: red"
    title="挂载内容-小程序"
    placement="right"
    width="600px"
  >
    <a-form
      ref="formRef"
      layout="vertical"
      :model="mobile_list"
      @finish="onFinish"
      @finishFailed="onFinishFailed"
    >
      <div class="mobile_item" v-for="(item, index) in mobile_list">
        <a-form-item
          style="margin-bottom: 10px !important"
          :label="`小程序_${index + 1}`"
          :name="[index, 'mobileUrl']"
          :rules="{
            required: true,
            message: '请输入小程序链接',
          }"
        >
          <a-auto-complete
            v-model:value="mobile_list[index].mobileUrl"
            allowClear
            placeholder="请输入小程序链接"
            :options="mobileUrlOptions"
            @focus="handleSearchChange(index, mobile_list[index].mobileUrl)"
            @search="handleSearchChange(index, $event)"
            @change="handMoileChange(index)"
          >
            <template #option>
              <a-row v-for="item in mobileUrlOptions" :key="index">
                <a-col>
                  <img
                    :src="item?.poster?.url_list[0]"
                    style="width: 44px; height: 44px; margin-right: 5px"
                  />
                </a-col>
                <a-col>
                  <div>{{ item.name }}</div>
                  <div style="color: rgba(28, 31, 35, 0.55); font-size: 12px">
                    {{ item.summary }}
                  </div>
                </a-col>
              </a-row>
            </template>
          </a-auto-complete>
        </a-form-item>
        <delete-outlined class="delet_btn" @click="deleteHandle(index)" />
      </div>

      <!-- 添加成片标题按钮 -->
      <a-button style="margin-top: 10px" block 
      :disabled="useType == 'oneAccount' && mobile_list.length >= 1"
      @click="addMobile"
        ><plus-outlined />添加小程序</a-button
      >
    </a-form>
    <template #footer>
      <div style="text-align: right">
        <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
        <a-button type="primary" @click="submitHandle">确定</a-button>
      </div>
    </template>
  </a-drawer>
</template>

<script>
import { defineComponent, ref, reactive, toRefs, createVNode } from "vue";
import {
  PlusOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import utils from "../../../../common/utils/utils";
import request from "../../../../common/utils/request";
import { Modal } from "ant-design-vue";
export default defineComponent({
  props: {
    mobileList: {
      type: Array,
      default: [],
    },
    anchor_mini: {
      type: Array,
      default: "",
    },
    accountList: {
      type: Array,
      default: [],
    },
  },
  components: {
    PlusOutlined,
    DeleteOutlined,
    ExclamationCircleOutlined,
  },
  setup(props, context) {
    const state = reactive({
      visible: false,
      mobile_list: [], //小程序链接集合
      anchorMini: [], //小程序信息集合
      account_list: [], //用户账户信息
      accountId: 0,
      mobileUrlOptions: [], //下拉信息

      // 批量挂载 还是单个挂载: accountList:批量, oneAccount:单个
      useType:'accountList',
      // 单个挂载的用户
      itemAccount: null,
    });
    // 打开弹窗
    const showDrawer = (params={}) => {
      const { itemAccount=null, useType='accountList' } = params
      state.useType = useType
      state.itemAccount = itemAccount

      if (useType == 'accountList') {
        if (props.mobileList.length) {
          state.mobile_list = JSON.parse(JSON.stringify(props.mobileList));
        } else {
          state.mobile_list = [{ mobileUrl: "" }];
        }
        console.log(props.mobileList, 'props.mobileList');
        console.log(props.anchor_mini, 'props.anchor_mini');
        console.log(props.accountList, 'props.accountList');
        
        state.anchorMini = JSON.parse(JSON.stringify(props.anchor_mini));
        state.account_list = JSON.parse(JSON.stringify(props.accountList));        
      } else {
        state.account_list = JSON.parse(JSON.stringify([itemAccount]))
        const anchorMini = itemAccount?.bind_info?.anchor_mini ? JSON.parse(JSON.stringify(itemAccount?.bind_info?.anchor_mini)) : []
        state.anchorMini =  anchorMini
        state.mobile_list = [{ mobileUrl: itemAccount?.bind_info?.anchor_mini?.[0]?.mobileUrl || '' }]
      }
      
      state.visible = true;
    };
    // 关闭弹窗
    const onClose = () => {
      state.visible = false;
      formRef.value.resetFields();
    };
    let time = null;
    const handleSearchChange = (index, url) => {
      if (!url) {
        state.mobileUrlOptions = [];
        state.accountId = 0;
        return;
      }
      if (!state.account_list.length) {
        message.warn("请选择账号");
        return;
      }



      let onLine = state.account_list.filter((item) => item.status == 1);
      if (!onLine.length) {
        onLine = state.account_list.filter((item) => item.status == 0);
      }
      state.accountId = onLine[0].id;
      if (time) {
        clearTimeout(time);
      }
      time = setTimeout(() => {
        getDouyinMobile(onLine[0].id, url, index);
      }, 500);
    };
    const getDouyinMobile = (id, url, index) => {
      request
        .get("/work_ai", "/org/platform/douyin/mobile", { id, url })
        .then((res) => {
          console.log(res,'挂载详情');
          
          if (res) {        
            // 如果没有挂载权限 则进行提示
            if (!res.data.anchor_list[0]?.enable_mount && res.data.anchor_list[0]?.reason) {
              message.error(res.data.anchor_list[0]?.reason)
            }
            state.mobileUrlOptions = res.data.anchor_list.map((item) => {
              return {
                label: item.name,
                value: state.mobile_list[index].mobileUrl,
                ...item,
              };
            });
            console.log(state.mobileUrlOptions);
            const extra = JSON.parse(res.data.anchor_list[0].extra);
            state.anchorMini[index] = {
              anchor_id: res.data.anchor_list[0].id, //小程序id
              Query: extra.Query,
              Title: extra.Title,
              Token: extra.Token,
            };
            console.log(state.anchorMini);
          }
        });
    };
    const formRef = ref();

    const submitHandle = () => {
      formRef.value
        .validate()
        .then(async (res) => {

          if (!state.anchorMini?.[0]?.anchor_id) {
            return message.error('未发现小程序信息')
          }

          if (state.useType == 'oneAccount') {
            // 小程序 name
            state.anchorMini[0].name = state.mobileUrlOptions?.[0]?.name || ''
            // 存放 小程序信息链接
            state.anchorMini[0].mobileUrl = state.mobile_list[0].mobileUrl
            const params = {
              id: state.itemAccount.id,
              anchor_mini: state.anchorMini,
            }
            console.log(params,'更新账号绑定的信息参数');

            // return
          const res  = await  request
              .put("/work_ai", "/user/platformAccount/user/update", params)
            console.log(res, '更新结果');
            state.visible = false;
            context.emit('updateItemAccount',params)
          } else {
            let params = {
              mobileList: state.mobile_list,
              anchor_mini: state.anchorMini,
            };
            state.visible = false;
            context.emit("success", params);
          }


        })
        .catch((err) => {
          console.log(err);
        });
    };
    const handMoileChange = (index) => {
      if (!state.mobile_list[index].mobileUrl) {
        if (state.anchorMini.length > 0) {
          state.anchorMini.splice(index, 1);
          console.log(state.anchorMini);
        }
      }
    };
    const deleteHandle = (index) => {
      if (state.mobile_list.length == 1) {
        return message.warning("至少保留一个小程序链接");
      } else {
        Modal.confirm({
          title: "删除小程序链接",
          icon: createVNode(ExclamationCircleOutlined),
          content: "确定删除小程序链接吗？",
          cancelText: "取消",
          okText: "确定",
          onOk() {
            state.mobile_list.splice(index, 1);
            state.anchorMini.splice(index, 1);
            message.success("删除成功");
          },
          onCancel() {},
        });
      }
    };
    const addMobile = () => {
      state.mobile_list.push({
        mobileUrl: "",
      });
    };
    // 添加标题
    return {
      ...toRefs(state),
      formRef,
      showDrawer,
      onClose,
      submitHandle,
      time,
      handleSearchChange,
      getDouyinMobile,
      addMobile,
      handMoileChange,
      deleteHandle,
    };
  },
});
</script>

<style lang="less" scoped>
.mobile_item {
  position: relative;
  .delet_btn {
    position: absolute;
    right: 0;
    top: 0;
    &:hover {
      color: var(--ss-primary-color);
    }
  }
}
</style>
